package cmd

import (
	"fmt"
	"gitee.com/wuennan/cloudstation/store"
	"gitee.com/wuennan/cloudstation/store/provider/aliyun"
	"gitee.com/wuennan/cloudstation/store/provider/qiniu"
	"github.com/AlecAivazis/survey/v2"
	"github.com/spf13/cobra"
	"time"
)

var (
	buckName       string
	uploadFilePath string
	bucketEndpoint string
	accessID    string
	accessKey   string
)

var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "Upload File to cloudstation",
	Long:  "Upload File to cloudstation",
	RunE: func(cmd *cobra.Command, args []string) error {
		p, err := getProvider()
		if err != nil {
			return err
		}
		day := time.Now().Format("20060102")
		objectKey := day + uploadFilePath
		err = p.UploadFile(buckName, objectKey, uploadFilePath)
		if err != nil {
			return err
		}
		return nil
	},
}

func getCloudSk() {
	prompt := &survey.Password{
		Message: "请输入云厂商access key: ",
	}
	survey.AskOne(prompt, &accessKey)
}

func getProvider() (p store.Uploader, err error) {
	switch ossProvider {
	case "aliyun":
		fmt.Printf("上传云商: 阿里云[%s]\n", bucketEndpoint)
		getCloudSk()
		fmt.Printf("上传用户: %s\n", accessID)
		p, err := aliyun.NewUploader(bucketEndpoint, accessID, accessKey)
		return p, err
	case "qiniu":
		fmt.Printf("上传云商: 七牛云[%s]\n", bucketEndpoint)
		getCloudSk()
		fmt.Printf("上传用户: %s\n", accessID)
		p, err := qiniu.NewUploader(accessID, accessKey)
		return p,err
	default:
		return nil, fmt.Errorf("unkonw oss privider")
	}
}


func init() {
	uploadCmd.PersistentFlags().StringVarP(&uploadFilePath, "file_path", "f", "", "Input file path or name")
	uploadCmd.PersistentFlags().StringVarP(&buckName, "bucket_name", "b", "", "Input buckName")
	uploadCmd.PersistentFlags().StringVarP(&bucketEndpoint, "bucket_endpoint", "e", "", "Ali endpoint,if Qiniu keep nil")
	uploadCmd.PersistentFlags().StringVarP(&accessID, "access_id", "i", "", "The Access ID")
	RootCmd.AddCommand(uploadCmd)
}
